﻿function ClsAdminHelper() {
    var self = this;

    // variable
    self.GlobalData = null;
    self.ViewModel = null;
    self.Table = null;

    self.PageIndex = 0;
    self.PageSize = 0;
    self.Total = 0;

    // config
    self.LoadListUrl = "";
    self.LoadDetailUrl = "";
    self.ManageUrl = "";
    self.UpdateActiveUrl = "";
    self.DeleteUrl = "";  

    self.CustomLoadList = false;
    self.CustomLoadDetail = false;
    self.CustomManage = false;
    self.CustomDelete = false;

    self.CanSort = false;
    self.SortColumnName = "";
    self.SortColumn = 0;
    self.SortAscending = true;

    self.DialogWidth = 800;
    self.DialogPosition = ["middle", "center"];
}

// function
ClsAdminHelper.prototype.Init = function (LoadListUrl, PageSize) {
    var self = this;

    self.LoadListUrl = LoadListUrl;
    self.PageSize = parseInt(PageSize);

    google.load('visualization', '1', { packages: ['table'] });
    google.setOnLoadCallback(function () {
        self.LoadList(0);
    });

    self.AddCssToRequiredField();

    $('#dialog-model').bind('dialogclose', function (event) {
        self.LoadList(self.PageIndex);
    });
}

ClsAdminHelper.prototype.DisplayCallBackSuccess = function () {
    // define in runtime
}

ClsAdminHelper.prototype.LoadList = function (PageIndex) {
    var self = this;

    if (PageIndex != null) {
        self.PageIndex = PageIndex;
    }
    else {
        self.PageIndex = 0;
    }

    var data;
    if (!self.CustomLoadList) {
        data = { pageIndex: self.PageIndex, orderClause: self.GetOrderClause() };
    }
    else {
        data = self.GetCustomLoadListData();
    }

    $.ajax({
        url: self.LoadListUrl,
        data: JSON.stringify(data),
        type: 'POST',
        contentType: 'application/json',
        success: function (result) {
            self.DisplayCallBackSuccess(result);
            self.LoadPagination();
            self.RemoveCssDisabledSortingColumn();
        },
        error: function (result) {
            CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
        }
    });
}

// private
ClsAdminHelper.prototype.LoadPagination = function () {
    var self = this;

    var html = "";
    $("#pagination-list-button").html(html);
    var totalPage = Math.ceil(self.Total / self.PageSize);

    if (totalPage > 1) {
        // first page
        if (self.PageIndex == 0) {
            html = "<a class='button disabled'><<</a>"
                        + "<a class='button disabled'><</a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (self.PageIndex + 1) + ");' class='button'>></a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (totalPage - 1) + ");' class='button'>>></a>";
        }
            // last page
        else if (self.PageIndex == (totalPage - 1)) {
            html = "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(0);' class='button'><<</a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (self.PageIndex - 1) + ");' class='button'><</a>"
                        + "<a class='button disabled'>></a>"
                        + "<a class='button disabled'>>></a>";
        }
        else {
            html = "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(0);' class='button'><<</a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (self.PageIndex - 1) + ");' class='button'><</a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (self.PageIndex + 1) + ");' class='button'>></a>"
                        + "<a href='javascript:void(0);' onclick='AdminHelper.LoadList(" + (totalPage - 1) + ");' class='button'>>></a>";
        }

        $("#pagination-list-button").html(html);
    }

    $("#page-index").html(self.PageIndex + 1);
    $("#total-pages").html(totalPage);
    $("#total-pages").digits();
    $("#total-items").html(self.Total);
    $("#total-items").digits();
}

ClsAdminHelper.prototype.RemoveCssDisabledSortingColumn = function () {
    var self = this;

    $(".google-visualization-table-th input:hidden").each(function () {
        if ($(this).val() == "disable-sorting") {
            $(this).parent().removeClass("google-visualization-table-sorthdr");
        }
    });
}

ClsAdminHelper.prototype.LoadDetailData = function (id) {
    var self = this;

    if (id == null) {
        if (self.CheckValidSelection()) {
            var id = self.GetArrId()[0];
        }
        else {
            return;
        }
    }

    // clear selection if status is Create data
    if (id == -1) {
        if (self.Table != null) {
            self.Table.setSelection(null);
        }
    }

    var data;
    if (!self.CustomLoadDetail) {
        data = { id: id };
    }
    else {
        data = self.GetCustomLoadDetailData(id);
    }

    $.ajax({
        url: self.LoadDetailUrl,
        data: JSON.stringify(data),
        type: 'POST',
        contentType: 'application/json',
        success: function (result) {
            if (result.Message == null || result.Message == "") {
                // ko.cleanNode(document.getElementById("dialog-model"));
                self.ReformatJsonData(result.Result);

                var isFirst = false;
                if (self.ViewModel == null) {
                    isFirst = true;
                }

                if (isFirst) {
                    self.ViewModel = ko.mapping.fromJS(result.Result);
                    ko.applyBindings(self.ViewModel, document.getElementById("dialog-model"));
                }
                else {
                    ko.mapping.fromJS(result.Result, self.ViewModel);
                }

                $("#dialog-model").dialog({
                    resizable: false,
                    width: self.DialogWidth,
                    position: self.DialogPosition,
                    buttons: {
                        "Ok": function () {
                            self.ManageData(false);
                        },
                        "Cancel": function () {
                            $(this).dialog("close");
                        },
                        "Apply": function () {
                            self.ManageData(true);
                        }
                    }
                });
            }
            else {
                CommonHelper.ShowMsg("Error: " + result.Message, MsgIconType.Error);
            }
        },
        error: function (result) {
            CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
        }
    });
}

ClsAdminHelper.prototype.ReformatJsonData = function () {
    // define in runtime
}

ClsAdminHelper.prototype.ManageData = function (isApply) {
    var self = this;

    var $form = $("#dialog-model form");

    if ($form.valid()) {
        var data;
        var msg = null;

        if (isApply) {
            msg = CommonPhrase.Success;
        }

        if (!self.CustomManage) {
            var unmappedViewModel = ko.mapping.toJS(self.ViewModel);
            data = { detail: unmappedViewModel };
        }
        else {
            var customData = self.GetCustomManageData();
            data = { detail: customData };
        }

        $.ajax({
            url: self.ManageUrl,
            data: JSON.stringify(data),
            type: 'POST',
            contentType: 'application/json',
            beforeSend: function () {
                CommonHelper.AjaxLoading();
            },
            success: function (result) {
                CommonHelper.StopAjaxLoading();
                self.ProcessCallBackSuccess(result, msg, isApply);
            },
            error: function (result) {
                CommonHelper.StopAjaxLoading();
                CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
            }
        });
    }
    else {
        // focus on error input
        var inp = $("#dialog-model form .input-validation-error:first").get(0);

        if (inp) {
            inp.focus();
        }
    }
}

ClsAdminHelper.prototype.DetailData = function (id) {
    var self = this;

    if (id == null) {
        if (self.CheckValidSelection()) {
            var id = self.GetArrId()[0];
        }
        else {
            return;
        }
    }

    var data;
    if (!self.CustomLoadDetail) {
        data = { id: id };
    }
    else {
        data = self.GetCustomLoadDetailData(id);
    }

    $.ajax({
        url: self.LoadDetailUrl,
        data: JSON.stringify(data),
        type: 'POST',
        contentType: 'application/json',
        success: function (result) {
            if (result.Message == null || result.Message == "") {
                self.ReformatJsonData(result.Result);
                self.ViewModel = ko.mapping.fromJS(result.Result);
                ko.applyBindings(self.ViewModel);

                $("#dialog-model-detail").dialog({
                    resizable: false,
                    width: self.DialogWidth,
                    position: self.DialogPosition
                });
            }
            else {
                CommonHelper.ShowMsg("Error: " + result.Message, MsgIconType.Error);
            }
        },
        error: function (result) {
            CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
        }
    });
}

ClsAdminHelper.prototype.GetCustomLoadListData = function () {
    // define in runtime
}

ClsAdminHelper.prototype.GetCustomLoadDetailData = function () {
    // define in runtime
}

ClsAdminHelper.prototype.GetCustomManageData = function () {
    // define in runtime
}

ClsAdminHelper.prototype.GetCustomDeleteData = function () {
    // define in runtime
}

ClsAdminHelper.prototype.UpdateActiveData = function (IsActive) {
    var self = this;

    if (self.CheckValidSelection()) {
        var arrId = self.GetArrId();
        var data = { arrId: arrId, isActive: IsActive };

        $.ajax({
            url: self.UpdateActiveUrl,
            data: JSON.stringify(data),
            type: 'POST',
            contentType: 'application/json',
            beforeSend: function () {
                CommonHelper.AjaxLoading();
            },
            success: function (result) {
                CommonHelper.StopAjaxLoading();
                self.ProcessCallBackSuccess(result);
                self.LoadList(self.PageIndex);
            },
            error: function (result) {
                CommonHelper.StopAjaxLoading();
                CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
            }
        });
    }
}

ClsAdminHelper.prototype.DeleteData = function (id) {
    var self = this;

    if (id != null || self.CheckValidSelection()) {
        if (confirm(CommonPhrase.ConfirmDelete) == true) {
            var arrId;
            
            if (id != null) {
                arrId = [ id ];
            }
            else {
                arrId = self.GetArrId();
            }

            var data;
            if (!self.CustomDelete) {
                data = { arrId: arrId };
            }
            else {
                data = self.GetCustomDeleteData(arrId);
            }

            $.ajax({
                url: self.DeleteUrl,
                data: JSON.stringify(data),
                type: 'POST',
                contentType: 'application/json',
                beforeSend: function () {
                    CommonHelper.AjaxLoading();
                },
                success: function (result) {
                    CommonHelper.StopAjaxLoading();
                    self.ProcessCallBackSuccess(result);
                    self.LoadList();
                },
                error: function (result) {
                    CommonHelper.StopAjaxLoading();
                    CommonHelper.ShowMsg("Error: " + CommonPhrase.CommonError, MsgIconType.Error);
                }
            });
        }
    }
}

// private
ClsAdminHelper.prototype.CheckValidSelection = function () {
    var self = this;

    var arrSelection = self.Table.getSelection();

    if (arrSelection.length <= 0) {
        CommonHelper.ShowMsg("Error: " + CommonPhrase.NoneSelection, MsgIconType.Error);
        return false;
    }

    return true;
}
 
// private
ClsAdminHelper.prototype.GetArrId = function () {
    var self = this;

    var arrId = new Array();

    // if (self.Table.hasOwnProperty("getSelection")) {
    if (self.Table != null) {
        var arrSelection = self.Table.getSelection();

        for (var i = 0; i < arrSelection.length; i++) {
            var rowIndex = (arrSelection[i].row) + 1;
            var id = parseInt($("#table-list table tr:eq(" + rowIndex + ")").children("td:eq(1)").first().html());

            arrId.push(id);
        }
    }

    return arrId;
}

ClsAdminHelper.prototype.GetArrIndex = function () {
    var self = this;

    var arrSelection = self.Table.getSelection();
    var arrIndex = new Array();

    for (var i = 0; i < arrSelection.length; i++) {
        var rowIndex = (arrSelection[i].row) + 1;
        arrIndex.push(rowIndex);
    }

    return arrIndex;
}    
   
// private
ClsAdminHelper.prototype.ProcessCallBackSuccess = function (result, msg, isApply) {
    var self = this;
    var arrId = self.GetArrId();

    if (result.Message == null || result.Message == "") {
        if (msg != null) {
            alert(msg);
        }

        if (isApply != null) {
            // btnOk
            if (!isApply) {
                $("#dialog-model").dialog("close");
            }
            // btnAppy, status: create
            else if (arrId == null || arrId.length <= 0) {
                self.LoadDetailData(-1);
            }
                // btnAppy, status: edit
            else {
                self.LoadDetailData();
            }
        }
    }
    else {
        CommonHelper.ShowMsg("Error: " + result.Message, MsgIconType.Error);
    }
}
    
// private
ClsAdminHelper.prototype.AddCssToRequiredField = function () {
    $(".editor-label").remove();
    $(".field-validation-valid").remove();
    $("input:text[data-val-required],input:password[data-val-required]").parent().prev().children("label").append(" <span class='required'>(*)</span>");
}

ClsAdminHelper.prototype.DrawTable = function (data) {
    var self = this;

    if (!self.CanSort) {
        self.Table.draw(
            data,
            {
                showRowNumber: true,
                allowHtml: true,
                sort: "disable",
                cssClassNames: { oddTableRow: "oddTableRow", selectedTableRow: "selectedTableRow" },
                width: 1000
            }
        );
    }
    else {
        var addListener = google.visualization.events.addListener;
        addListener(
            self.Table,
            'sort',
            function (e) {
                self.SortColumn = e['column'];
                self.SortAscending = e['ascending'];

                if ($("#column" + self.SortColumn).val() != "disable-sorting") {
                    self.LoadList();
                }
            }
        );

        self.Table.draw(
            data,
            {
                showRowNumber: true,
                allowHtml: true,
                sort: "event",
                sortColumn: self.SortColumn,
                sortAscending: self.SortAscending,
                cssClassNames: { oddTableRow: "oddTableRow", selectedTableRow: "selectedTableRow" },
                width: 1000
            }
        );
    }
}

ClsAdminHelper.prototype.GetOrderClause = function () {
    var self = this;

    var result = "";

    var columnName = $(".column" + self.SortColumn).val();

    if (typeof (columnName) == 'undefined') {
        columnName = self.SortColumnName;
    }

    if (columnName != "disable-sorting") {
        result = "order by " + columnName + " " + (self.SortAscending ? "asc" : "desc");
    }
    else {
        result = "disable-sorting";
    }

    return result;
}

ClsAdminHelper.prototype.GetRowButton = function (opts) {
    var html = "";

    var defaults = {
        Id: -1,
        Edit: false,
        Detail: false,
        Delete: false
    };

    var settings = $.extend({}, defaults, opts);

    if (settings.Edit) {
        html += "<a class='btn-row btn-detail' href='javascript:void(0);' onclick='AdminHelper.LoadDetailData(" + settings.Id + ");'>Edit</a>&nbsp";
    }

    if (settings.Detail) {
        html += "<a class='btn-row btn-detail' href='javascript:void(0);' onclick='AdminHelper.DetailData(" + settings.Id + ");'>Detail</a>&nbsp";
    }

    if (settings.Delete) {
        html += "<a class='btn-row btn-delete' href='javascript:void(0);' onclick='AdminHelper.DeleteData(" + settings.Id + ");'>Delete</a>&nbsp";
    }

    return html;
}

var AdminHelper = new ClsAdminHelper();